#
# Copyright:: Copyright (c) 2017 GitLab Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

require "#{base_path}/embedded/cookbooks/package/libraries/deprecations"
require 'json'
require_relative "lib/gitlab_ctl/util"

add_command 'check-config', 'Check if there are any configuration in gitlab.rb that is removed in specified version', 2 do |cmd_name|
  # Extracting JSON from the fqdn.json file generated by reconfigure.
  # Since we can't have fqdn info here, we do a glob and choose the first json
  # file. Reconfigure removes existing json file before creating a new one, so
  # it is safe enough.
  node_json_file = Dir.glob("#{base_path}/embedded/nodes/*.json")[0]
  unless node_json_file
    log "JSON file with existing configuration not found inside #{base_path}/embedded/nodes."
    log "Skipping config check."
    Kernel.exit 0
  end

  if GitlabCtl::Util.public_attributes_broken?
    log 'Public attributes file is missing, run gitlab-ctl reconfigure to re-create it.'
    Kernel.exit 1
  end

  node_json = JSON.parse(File.read(node_json_file))
  unless node_json.key?("normal")
    log "Malformed configuration JSON file found at #{node_json_file}."
    log "This usually happens when your last run of `gitlab-ctl reconfigure` didn't complete successfully."
    log "This file is used to check if any of the unsupported configurations are enabled,"
    log "and hence require a working reconfigure before upgrading."
    log "Please run `sudo gitlab-ctl reconfigure` to fix it and try again."
    Kernel.exit 1
  end
  existing_config = node_json['normal']

  messages = Gitlab::Deprecations.check_config(parse_version, existing_config, :removal)
  Kernel.exit 0 if messages.empty?

  log messages.join("\n")
  log 'Deprecations found. Please correct them and try again.'
  Kernel.exit 1
end

def parse_version
  version = ""
  OptionParser.new do |opts|
    opts.on('-vVER', '--version=VER', 'Version to be installed') do |input_version|
      version = input_version
    end
  end.parse!(ARGV)
  version
end
